<template>
  <div class="user-list-container">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="卡id">
            <el-input
              v-model="searchForm.CardId"
              placeholder="请输入卡id"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="持卡人id">
            <el-input
              v-model="searchForm.CardholderId"
              placeholder="请输入持卡人id"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="完整卡号">
            <el-input
              v-model="searchForm.CompleteCardNumber"
              placeholder="请输入完整卡号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="卡号后四位">
            <el-input
              v-model="searchForm.LastFourCardNumber"
              placeholder="请输入卡号后四位"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="商户">
            <el-select
              v-model="searchForm.MerchantId"
              placeholder="请选择商户"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in merchantIdOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="卡片状态">
            <el-select
              v-model="searchForm.CardStatus"
              placeholder="请选择卡片状态"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in cardStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上游平台配置">
            <el-select
              v-model="searchForm.UpstreamPlatformId"
              placeholder="请选择上游平台配置"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in upstreamPlatformOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="卡类型">
            <el-select
              v-model="searchForm.CardFormFactor"
              placeholder="请选择卡类型"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in cardFormFactorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 商户表格 -->
      <el-table 
        :data="list" 
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        empty-text="暂无数据"
      >
        <el-table-column prop="CardId" label="卡片id(uuid)" width="220">
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.CardId" placement="top">
                <span class="text-ellipsis">{{ scope.row.CardId }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.CardId, 'CardId')"
                class="copy-btn"
                v-if="scope.row.CardId"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="CardBin" label="卡bin（卡头）" show-overflow-tooltip />
        <el-table-column prop="CardCurrency" label="卡片币种"/>
        <el-table-column prop="CardScheme" label="卡scheme" />
        <el-table-column prop="AvailableBalance" label="可用余额" />
        <el-table-column prop="CardFormFactor" label="卡类型" />
        <el-table-column prop="CardModeType" label="卡片模式" />
        <el-table-column prop="CardStatus" label="卡片状态" />
        <el-table-column prop="CardNumber" label="卡号" width="120" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.CardNumber || scope.row.CompleteCardNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Merchant" label="商户名称" width="120">
          <template #default="scope">
            <span>{{ scope.row.Merchant?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpstreamPlatform" label="上游平台名称" width="120">
          <template #default="scope">
            <span>{{ scope.row.UpstreamPlatform?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="CreatedAtString" label="创建时间" sortable show-overflow-tooltip />
        <el-table-column label="操作" width="340" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleUpdateStatus(scope.row)">更改状态</el-button>
            <el-button type="text" size="small" @click="handleRefreshCard(scope.row)">刷新卡片</el-button>
            <el-button type="text" size="small" @click="handleActivateCard(scope.row)" v-if="scope.row.InternalCardFormFactor === 2">激活</el-button>
            <el-button type="text" size="small" @click="handleUpdateCard(scope.row)">更新卡片</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 更改卡片状态对话框 -->
    <el-dialog
      title="更改卡片状态"
      v-model="updateStatusDialogVisible"
      width="400px"
      :before-close="handleCloseUpdateStatus"
    >
      <el-form
        ref="updateStatusFormRef"
        :model="updateStatusForm"
        :rules="updateStatusRules"
        label-width="100px"
      >
        <el-form-item label="卡片状态" prop="CardStatus">
          <el-select
            v-model="updateStatusForm.CardStatus"
            placeholder="请选择卡片状态"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in updateCardStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseUpdateStatus">取消</el-button>
          <el-button type="primary" @click="handleUpdateStatusSubmit" :loading="updateStatusLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 激活卡片对话框 -->
    <el-dialog
      title="激活卡片"
      v-model="activateDialogVisible"
      width="500px"
      :before-close="handleCloseActivate"
    >
      <el-form
        ref="activateFormRef"
        :model="activateForm"
        :rules="activateRules"
        label-width="120px"
      >
        <el-form-item label="激活码" prop="ActivationCode">
          <el-input v-model="activateForm.ActivationCode" placeholder="请输入激活码" />
        </el-form-item>
        <el-form-item label="免密支付金额" prop="NoPinPaymentAmount">
          <el-input-number v-model="activateForm.NoPinPaymentAmount" placeholder="请输入免密支付金额" :min="0" :step="0.01" :precision="2" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="Pin" prop="Pin">
          <el-input v-model="activateForm.Pin" placeholder="请输入Pin" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseActivate">取消</el-button>
          <el-button type="primary" @click="handleActivateSubmit" :loading="activateLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更新卡片对话框 -->
    <el-dialog
      title="更新卡片"
      v-model="updateCardDialogVisible"
      width="400px"
      :before-close="handleCloseUpdateCard"
    >
      <el-form
        ref="updateCardFormRef"
        :model="updateCardForm"
        :rules="updateCardRules"
        label-width="120px"
      >
        <el-form-item label="免密支付金额" prop="NoPinPaymentAmount">
          <el-input-number v-model="updateCardForm.NoPinPaymentAmount" :min="0" :step="0.01" :precision="2" controls-position="right" style="width: 100%" placeholder="请输入免密支付金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseUpdateCard">取消</el-button>
          <el-button type="primary" @click="handleUpdateCardSubmit" :loading="updateCardLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import { cardList, updateCardStatus, updateCardInfo, activateCard, updateCard } from '@/api/card'
import { upstreamPlatformList, merchantList, cardStatusList, updateCardStatusList } from '@/api/selectList'

// 响应式数据
const loading = ref(false)
const list = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const merchantIdOptions = ref([])
const upstreamPlatformOptions = ref([])
const cardStatusOptions = ref([])
const updateCardStatusOptions = ref([])
const updateStatusDialogVisible = ref(false)
const updateStatusFormRef = ref()
const updateStatusLoading = ref(false)
const cardFormFactorOptions = ref([
  {
    label: '虚拟卡',
    value: 'VIRTUAL',
  },
  {
    label: '实体卡',
    value: 'PHYSICAL',
  },
])
// 搜索表单
const searchForm = reactive({
  LastFourCardNumber: '',
  CompleteCardNumber: '',
  CardId: '',
  MerchantId: '',
  UpstreamPlatformId: '',
  CardStatus: null,
  CardholderId: null,
  CardFormFactor: '',
})

// 更改状态表单
const updateStatusForm = reactive({
  Id: null,
  CardStatus: ''
})

// 更改状态表单验证规则
const updateStatusRules = {
  CardStatus: [
    { required: true, message: '请选择卡片状态', trigger: 'change' }
  ]
}

// 激活卡片对话框与表单
const activateDialogVisible = ref(false)
const activateFormRef = ref()
const activateLoading = ref(false)
const activateForm = reactive({
  CardId: '',
  ActivationCode: '',
  NoPinPaymentAmount: null,
  Pin: ''
})
const activateRules = {
  ActivationCode: [
    { required: true, message: '请输入激活码', trigger: 'blur' }
  ],
  NoPinPaymentAmount: [
    { required: true, message: '请输入免密支付金额', trigger: 'change' }
  ],
  Pin: [
    { required: true, message: '请输入Pin', trigger: 'blur' }
  ]
}

// 更新卡片对话框与表单
const updateCardDialogVisible = ref(false)
const updateCardFormRef = ref()
const updateCardLoading = ref(false)
const updateCardForm = reactive({
  Id: null,
  NoPinPaymentAmount: null
})
const updateCardRules = {
  NoPinPaymentAmount: [
    { required: true, message: '请输入免密支付金额', trigger: 'change' }
  ]
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await cardList({
      ...searchForm,
      Page: currentPage.value,
      PageSize: pageSize.value,
    })
    if (res.code === 200) {
      list.value = res.data?.List || []
      total.value = res.data?.Total
    } else {
      ElMessage.error('获取商户列表失败')
    }
  } catch (error) {
    // ElMessage.error('获取商户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {    
    LastFourCardNumber: '',
    CompleteCardNumber: '',
    CardId: '',
    MerchantId: '',
    UpstreamPlatformId: '',
    CardStatus: null,
    CardholderId: null,
    CardFormFactor: '',
  })
  currentPage.value = 1
  getList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  getList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getList()
}

const getMerchantIdOptions = async () => {
  try {
    const res = await merchantList()
    if (res.code === 200) {
      merchantIdOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

const getCardStatusOptions = async () => {
  try {
    const res = await cardStatusList()
    if (res.code === 200) {
      const options = res.data && Object.entries(res.data).map(([value, label]) => ({
        label: label,
        value: value
      }));
      cardStatusOptions.value = options || []
    }
  } catch (error) {
    console.error(error)
  }
}

const getUpstreamPlatformOptions = async () => {
  try {
    const res = await upstreamPlatformList()
    if (res.code === 200) {      
      upstreamPlatformOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 获取更改状态选项
const getUpdateCardStatusOptions = async () => {
  try {
    const res = await updateCardStatusList()
    if (res.code === 200) {
      const options = res.data && Object.entries(res.data).map(([value, label]) => ({
        label: label,
        value: value
      }))
      updateCardStatusOptions.value = options || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 打开更改状态对话框
const handleUpdateStatus = (row) => {
  updateStatusForm.Id = row.Id
  updateStatusForm.CardStatus = ''
  updateStatusDialogVisible.value = true
}

// 关闭更改状态对话框
const handleCloseUpdateStatus = () => {
  updateStatusDialogVisible.value = false
  // 重置表单校验
  if (updateStatusFormRef.value) {
    updateStatusFormRef.value.resetFields()
  }
}

// 提交更改状态
const handleUpdateStatusSubmit = async () => {
  if (!updateStatusFormRef.value) return
  updateStatusLoading.value = true
  try {
    await updateStatusFormRef.value.validate()
    const res = await updateCardStatus({
      Id: updateStatusForm.Id,
      CardStatus: updateStatusForm.CardStatus
    })
    if (res.code === 200) {
      ElMessage.success('更改状态成功')
      updateStatusDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.message || '更改状态失败')
    }
  } catch (error) {
    console.error(error)
  } finally {
    updateStatusLoading.value = false
  }
}

// 刷新卡片
const handleRefreshCard = async (row) => {
  ElMessageBox.confirm(
    '确定要刷新该卡片信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await updateCardInfo({ Id: row.Id })
      if (res.code === 200) {
        ElMessage.success('刷新成功')
        getList()
      } else {
        ElMessage.error(res.message || '刷新失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消刷新',
      })
    })
}

// 打开激活卡片对话框
const handleActivateCard = (row) => {
  activateForm.CardId = row.CardId
  activateForm.ActivationCode = ''
  activateForm.NoPinPaymentAmount = null
  activateForm.Pin = ''
  activateDialogVisible.value = true
}

// 关闭激活卡片对话框
const handleCloseActivate = () => {
  activateDialogVisible.value = false
  // 重置表单校验
  if (activateFormRef.value) {
    activateFormRef.value.resetFields()
  }
}

// 提交激活卡片
const handleActivateSubmit = async () => {
  if (!activateFormRef.value) return
  activateLoading.value = true
  try {
    await activateFormRef.value.validate()
    const res = await activateCard({
      ActivationCode: activateForm.ActivationCode,
      CardId: activateForm.CardId,
      NoPinPaymentAmount: Number(activateForm.NoPinPaymentAmount),
      Pin: activateForm.Pin
    })
    if (res.code === 200) {
      ElMessage.success('激活卡片成功')
      activateDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.message || '激活卡片失败')
    }
  } catch (error) {
    console.error(error)
  } finally {
    activateLoading.value = false
  }
}

// 打开更新卡片对话框
const handleUpdateCard = (row) => {
  updateCardForm.Id = row.Id
  updateCardForm.NoPinPaymentAmount = row.NoPinPaymentAmountDecimal !== undefined ? Number(row.NoPinPaymentAmountDecimal) : null
  updateCardDialogVisible.value = true
}

// 关闭更新卡片对话框
const handleCloseUpdateCard = () => {
  updateCardDialogVisible.value = false
  // 重置表单校验
  if (updateCardFormRef.value) {
    updateCardFormRef.value.resetFields()
  }
}

// 提交更新卡片
const handleUpdateCardSubmit = async () => {
  if (!updateCardFormRef.value) return
  updateCardLoading.value = true
  try {
    await updateCardFormRef.value.validate()
    const res = await updateCard({
      Id: updateCardForm.Id,
      NoPinPaymentAmount: Number(updateCardForm.NoPinPaymentAmount)
    })
    if (res.code === 200) {
      ElMessage.success('更新卡片成功')
      updateCardDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.message || '更新卡片失败')
    }
  } catch (error) {
    console.error(error)
  } finally {
    updateCardLoading.value = false
  }
}
// 生命周期
onMounted(() => {
  getList()
  getMerchantIdOptions()
  getUpstreamPlatformOptions()
  getCardStatusOptions()
  getUpdateCardStatusOptions()
})

// 复制功能
const handleCopy = async (text, fieldName) => {
  try {
    if (!text) {
      ElMessage.warning('复制内容为空')
      return
    }
    
    // 使用现代浏览器的 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      ElMessage.success(`${fieldName}复制成功`)
    } else {
      // 降级方案：使用传统的 document.execCommand
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          ElMessage.success(`${fieldName}复制成功`)
        } else {
          ElMessage.error('复制失败')
        }
      } catch (err) {
        ElMessage.error('复制失败')
      }
      
      document.body.removeChild(textArea)
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-table__header-wrapper .cell) {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

/* 复制按钮样式 */
.copy-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.text-ellipsis {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.copy-btn {
  flex-shrink: 0;
  padding: 4px;
  margin: 0;
}

.copy-btn:hover {
  color: var(--el-color-primary);
}

/* 让表格滚动条始终显示 */
::v-deep(.el-table__body-wrapper .el-scrollbar__bar) {
  display: block!important;
}
:deep(.el-scrollbar__thumb) {
  background-color: #909399;
  opacity: 1;
}
:deep(.el-input-number.is-center .el-input__inner) {
  text-align: left;
}
</style>